package com.example.libbase.net.dl;

import android.text.TextUtils;

import com.example.libbase.utils.Logger;
import com.example.libbase.utils.PropertiesUtil;

import java.util.concurrent.TimeUnit;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import dagger.hilt.InstallIn;
import dagger.hilt.android.components.ApplicationComponent;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * TODO 学习Retrofit
 */
@Module
@InstallIn(ApplicationComponent.class) // 装载
public class NetWorkModule {

    /**
     * 创建Retrofit实例
     * @param client
     * @return
     */
    @Provides
    @Singleton // 单例
    public Retrofit provideRetrofit(OkHttpClient client) {
        String baseUrl = PropertiesUtil.getProperty("baseUrl");
        if(TextUtils.isEmpty(baseUrl)) {
            Logger.e("baseUrl is empty");
        }
        return new Retrofit.Builder()
                .baseUrl(baseUrl) // 定义后台服务地址
                .client(client)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // 数据转化
                .addConverterFactory(GsonConverterFactory.create()) // 数据解析 把具体数据转化为实体对象
                .build();
    }

    /**
     * 获取OkHttp实例
     * @return
     */
    @Provides
    @Singleton
    public OkHttpClient provideOkHttpClient() {
        // 拦截
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {

            }
        }).setLevel(HttpLoggingInterceptor.Level.BODY);

        return new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .connectTimeout(2, TimeUnit.SECONDS) // 连接超时
                .writeTimeout(120, TimeUnit.SECONDS) // 写入超时
                .readTimeout(60, TimeUnit.SECONDS) // 读取超时
                .build();
    }
}
